package com.wjb.xietong.server.topic;

import org.json.JSONObject;
import com.wjb.xietong.W3.HttpUtil;
import com.wjb.xietong.W3.JsonHttpResponseHandler;
import com.wjb.xietong.server.HeaderInfoResponse;
import com.wjb.xietong.server.IRequestParam;
import com.wjb.xietong.server.IRequestResultListener;
import com.wjb.xietong.server.IService;
import com.wjb.xietong.util.IDs;

public class ReplyService implements IService {
	private long uniqueID = 0l;
	private ReplyParam param = null;
	private IRequestResultListener listener = null;

	@Override
	public int request() {
		return HttpUtil.post(IDs.TOPIC_URL, param.parseData2Map(),
				new ReplyServiceListener());
	}

	@Override
	public void setParameter(long uniqueID, IRequestResultListener listener,
			IRequestParam param) {
		this.uniqueID = uniqueID;
		this.param = (ReplyParam) param;
		this.listener = listener;
	}

	public class ReplyServiceListener extends JsonHttpResponseHandler {
		@Override
		public void onSuccess(JSONObject response) {
			if (listener instanceof IRequestResultListener) {
				if (ReplyResponse.instance().parseJsonObj(response)) {
					listener.requestSuccess(uniqueID);
					return;
				}
				HeaderInfoResponse headerInfo = ReplyResponse.instance()
						.getHeaderInfo();
				listener.requestFaield(uniqueID, null == headerInfo ? ""
						: headerInfo.getErrorCode(), null == headerInfo ? ""
						: headerInfo.getErrorMsg());
			}
		}

		@Override
		public void onFailure(int errorCode, Throwable e,
				JSONObject errorResponse) {
			if (listener instanceof IRequestResultListener) {
				listener.requestFaield(uniqueID, String.valueOf(errorCode),
						e == null ? "" : e.getMessage());
			}
		}
	}

}
